package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.ScheduleRule;
import com.example.chamberlainserver.Service.ScheduleRuleService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 排班规则控制器
 */
@RestController
@RequestMapping("/schedule/rules")
public class ScheduleRuleController {

    @Autowired
    private ScheduleRuleService scheduleRuleService;

    /**
     * 添加排班规则
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> addScheduleRule(@RequestBody ScheduleRule scheduleRule) {
        try {
            // 设置创建人
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 这里需要根据username获取userId，暂时设置为1
            scheduleRule.setCreatedBy(1);
            
            boolean success = scheduleRuleService.addScheduleRule(scheduleRule);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("添加排班规则成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("添加排班规则失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加排班规则失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取排班规则
     */
    @GetMapping("/get/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<ScheduleRule>> getScheduleRuleById(@PathVariable String id) {
        try {
            ScheduleRule scheduleRule = scheduleRuleService.getScheduleRuleById(id);
            
            if (scheduleRule != null) {
                return ResponseEntity.ok(ApiResponse.success("获取排班规则成功", scheduleRule));
            } else {
                return ResponseEntity.ok(ApiResponse.error(404, "排班规则不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取排班规则失败: " + e.getMessage()));
        }
    }

    /**
     * 根据名称获取排班规则列表
     */
    @GetMapping("/name/{name}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleRule>>> getScheduleRulesByName(@PathVariable String name) {
        try {
            List<ScheduleRule> scheduleRules = scheduleRuleService.getScheduleRulesByName(name);
            return ResponseEntity.ok(ApiResponse.success("获取排班规则列表成功", scheduleRules));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取排班规则列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取排班规则列表（默认返回所有活跃规则）
     */
    @GetMapping
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleRule>>> getScheduleRules() {
        try {
            List<ScheduleRule> scheduleRules = scheduleRuleService.getActiveScheduleRules();
            return ResponseEntity.ok(ApiResponse.success("获取排班规则列表成功", scheduleRules));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取排班规则列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有活跃的排班规则
     */
    @GetMapping("/active")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleRule>>> getActiveScheduleRules() {
        try {
            List<ScheduleRule> scheduleRules = scheduleRuleService.getActiveScheduleRules();
            return ResponseEntity.ok(ApiResponse.success("获取活跃排班规则列表成功", scheduleRules));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取活跃排班规则列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取所有排班规则
     */
    @GetMapping("/all")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleRule>>> getAllScheduleRules() {
        try {
            List<ScheduleRule> scheduleRules = scheduleRuleService.getAllScheduleRules();
            return ResponseEntity.ok(ApiResponse.success("获取所有排班规则列表成功", scheduleRules));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取所有排班规则列表失败: " + e.getMessage()));
        }
    }

    /**
     * 更新排班规则
     */
    @PutMapping("/update")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateScheduleRule(@RequestBody ScheduleRule scheduleRule) {
        try {
            boolean success = scheduleRuleService.updateScheduleRule(scheduleRule);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("更新排班规则成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新排班规则失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新排班规则失败: " + e.getMessage()));
        }
    }

    /**
     * 删除排班规则
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteScheduleRule(@PathVariable String id) {
        try {
            boolean success = scheduleRuleService.deleteScheduleRule(id);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除排班规则成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除排班规则失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除排班规则失败: " + e.getMessage()));
        }
    }

    /**
     * 启用/禁用排班规则
     */
    @PutMapping("/status/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateScheduleRuleStatus(
            @PathVariable String id,
            @RequestParam Boolean isActive) {
        try {
            boolean success = scheduleRuleService.updateScheduleRuleStatus(id, isActive);
            
            if (success) {
                String action = isActive ? "启用" : "禁用";
                return ResponseEntity.ok(ApiResponse.success(action + "排班规则成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新排班规则状态失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新排班规则状态失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询排班规则列表
     */
    @GetMapping("/pagedList")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<PageResult<ScheduleRule>>> getPagedScheduleRuleList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "isActive", required = false) Boolean isActive,
            @RequestParam(value = "createdBy", required = false) Integer createdBy) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("pageSize", pageSize);
            params.put("offset", (current - 1) * pageSize);
            
            if (name != null && !name.trim().isEmpty()) {
                params.put("name", name.trim());
            }
            if (isActive != null) {
                params.put("isActive", isActive);
            }
            if (createdBy != null) {
                params.put("createdBy", createdBy);
            }
            
            PageResult<ScheduleRule> pageResult = scheduleRuleService.getPagedScheduleRuleList(params);
            return ResponseEntity.ok(ApiResponse.success("获取排班规则列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取排班规则列表失败: " + e.getMessage()));
        }
    }

    /**
     * 验证排班规则配置
     */
    @PostMapping("/validate")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Boolean>> validateScheduleRules(@RequestBody List<ScheduleRule> rules) {
        try {
            boolean isValid = scheduleRuleService.validateScheduleRules(rules);
            
            if (isValid) {
                return ResponseEntity.ok(ApiResponse.success("排班规则配置验证通过", true));
            } else {
                return ResponseEntity.ok(ApiResponse.success("排班规则配置验证失败", false));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("验证排班规则配置失败: " + e.getMessage()));
        }
    }
}